<template>
  <div>
    <a-table
      :columns="columns"
      :data-source="dataSource" 
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: skeys => selectedRowKeys = skeys }"
      :pagination="false" 
      bordered
    >
      <template slot="title" slot-scope="currentPageData">
        <a-button type="primary" @click="isAdd = true">添加节点</a-button>
        <a-button type="primary" @click="onEdit">编辑节点</a-button>
        <a-button type="danger" @click="onDel">删除节点</a-button>
      </template>
    </a-table>

    <template v-if="isAdd">
      <flow-chart-node-editor :show.sync="isAdd" :is-edit="false" @on-close="init" />
    </template>  
    <template v-if="isEdit">
      <flow-chart-node-editor :show.sync="isEdit" :is-edit="true" :data="editData" @on-close="init" />
    </template>
  </div>
</template>

<script lang="es6">
const columns = [
  {
    title: '名称',
    dataIndex: 'name'
  }
];

module.exports = asyncRequire([
    'mixins',
    'alias!@PAGE/components/localNodes',
], function(MXS, NodeAPI, resolve, reject) {
  resolve({
    name: 'FlowChartNodeList',
    mixins: [MXS.CommonMixin],
    components: {
      FlowChartNodeEditor: load('./FlowChartNodeAE')
    },
    data () {
      return {
        columns: columns,
        dataSource: [],
        selectedRowKeys: [],
        isAdd: false,
        isEdit: false,
        editData: {}
      }
    },
    computed: {
    },
    mounted () {
      this.init();
    },
    methods: {
      init () {
        this.dataSource = [];
        NodeAPI.findAll().nodes.forEach(node => {
          this.dataSource.push(node);
        });
      },
      
      onEdit () {
        if(this.selectedRowKeys.length !== 1) {
          return this.$message.error('有且仅能选择一行');
        }
        this.editData = this.dataSource[this.selectedRowKeys[0]];
        this.isEdit = true;
      },

      onDel () {
        if(this.selectedRowKeys.length === 0) {
          return this.$message.error('至少选择一行');
        }
        this.$confirm({
          title: '提示',
          content: `确认删除选择的${this.selectedRowKeys.length}个节点吗?`,
          onOk: () => {
            var delNodes = this.dataSource.filter((item, index) => this.selectedRowKeys.findIndex(key => key === index) >= 0).map(node => node.id);
            NodeAPI.deleteNodes(delNodes);
            this.selectedRowKeys = [];
            this.init();
          }
        });
      }
    }
  });
});
</script>

<style scoped>
  
</style>
